import { _decorator, Asset, AssetManager, Label, ProgressBar, sys } from 'cc';
import { BundleConfig } from '../config/BundleConfig';
import { CommonConfig } from '../config/CommonConfig';
import { GameController } from '../controller/GameController';
import { HttpController } from '../controller/HttpController';
import { EventManager } from '../engine/EventManager';
import HotUpdate from '../engine/HotUpdate';
import { Logger } from '../engine/Logger';
import { ResourceManager } from '../engine/ResourceManager';
import { UI_Cache_Type, UI_Config } from '../engine/UI_Config';
import { UIManager } from '../engine/UIManager';
import VersionManager from '../engine/VersionManager';
import ViewBase from '../engine/ViewBase';
const { ccclass, property } = _decorator;

@ccclass('ui/ViewLoading')
export class ViewLoading extends ViewBase {

    //ui 配置 
    public static uiConfig: UI_Config = new UI_Config("ViewLoading",
        UI_Cache_Type.always, true, BundleConfig.main);

    private isHotUpdate: boolean = false; //是否热更新
    private needLoadList: Array<string> = []; //需要加载列表 
    private finishCallback: Function;   //加载完成回调函数
    private bundleName: string; //

    private progressBar: ProgressBar;
    private lbMsg: Label;
    private maxProgress: number = 0


    public onInitChild(isHotUpdate: boolean, needLoadList: Array<string> = [],
        bundleName: string = BundleConfig.main, finishCallback: Function = null) {
        this.isHotUpdate = isHotUpdate;
        this.needLoadList = needLoadList;
        this.bundleName = bundleName;
        this.finishCallback = finishCallback
        Logger.log("LoadingView.onInitChild", isHotUpdate, needLoadList);
    }

    onShow(): void {
        this.maxProgress = 0;
        this.progressBar = this.getChild(this.contentNode, "ProgressBar", ProgressBar);
        this.lbMsg = this.getChild(this.contentNode, "lbMsg", Label);
        Logger.log("LoadingView.onShow", this.contentNode, this.lbMsg);
        this.setProgress(0)
        this.setProgressTip("正在努力加载中...")
        if (this.isHotUpdate) {
            this.checkNetwork();
        } else {

        }
    }

    //监听热更新事件 
    protected registEventList(): void {
        EventManager.instance.on(HotUpdate.Event_On_NeedUpdate, this.onNeedUpdate, this);
        EventManager.instance.on(HotUpdate.Event_On_Progress, this.onUpdateProgress, this);
        EventManager.instance.on(HotUpdate.Event_On_Fail_Update, this.onUpdateFail, this);
        EventManager.instance.on(HotUpdate.Event_Finish_Update, this.onUpdateFinish, this);
        EventManager.instance.on(HotUpdate.Event_On_ALREADY_UP_TO_DATE, this.onUpdateFinish, this);
    }

    /**
     * 检查网络状态,没授权网络的要先授权网络权限 
     */
    private checkNetwork() {
        if (sys.getNetworkType() != sys.NetworkType.NONE) {
            this.getInitConfig();
        } else {
            this.scheduleOnce(() => {
                this.checkNetwork();
            }, 0.5)
        }
    }

    /**
     * 获取服务器配置信息
     */
    private getInitConfig() {
        this.setProgress(0)
        this.setProgressTip("正在获取服务器配置信息...");
        HttpController.getInitConfig((isOk: boolean) => {
            this.setProgress(1)
            this.setProgressTip("获取服务器配置成功...");
            if (sys.isNative) {
                VersionManager.instance.isOpenHotUpdate = isOk;
                UIManager.instance.showLoadingIcon();
                this.setProgress(0)
                this.setProgressTip("正在检查热更新文件...");
                ResourceManager.instance.load("project", null, null, (data: Asset) => {
                    // Logger.log("asset==", data);
                    UIManager.instance.hideLoadingIcon();
                    VersionManager.instance.init(data);
                    this.setProgressTip("正在对比版本号...");
                    VersionManager.instance.checkUpdate(0);
                })
            } else {
                VersionManager.instance.isOpenHotUpdate = false
                this.startLoadingLocal();
            }
        })
    }

    //设置加载 tips
    private setProgressTip(msg: string) {
        this.lbMsg.string = msg;
    }

    //设置加载进度
    private setProgress(progress: number) {
        if (this.progressBar) {
            this.progressBar.progress = progress;
        }
    }

    //需要热更新
    private onNeedUpdate(key: string) {
        Logger.log("onNeedUpdate=====", key, VersionManager.Config_Key);
        if (key == VersionManager.Config_Key[0]) {
            VersionManager.instance.startUpdate(0);
            this.setProgress(0);
            this.setProgressTip("需要更新文件...");
        }
    }

    //更新进度
    private onUpdateProgress(loadedFiles: number, totalFiles: number, key: string) {
        if (key == VersionManager.Config_Key[0]) {
            let progress: number = loadedFiles / totalFiles;
            if (progress > this.maxProgress) {
                this.maxProgress = progress
                this.setProgress(this.maxProgress)
            }
            let hadLoadMb: string = (loadedFiles / 1024 / 1024).toFixed(2) + "Mb";
            let totalMb: string = (totalFiles / 1024 / 1024).toFixed(2) + "Mb";
            this.setProgressTip("正在认真更新文件 " + (this.maxProgress * 100).toFixed(2) + "%(" + hadLoadMb + "/" + totalMb + ")");
        }
    }

    //更新失败
    private onUpdateFail(key: string) {
        if (key == VersionManager.Config_Key[0]) {
            Logger.warn("热更新失败========");
            UIManager.instance.showTip("热更新下载资源失败!");
            this.scheduleOnce(() => {
                GameController.instance.restartGame()
            }, 1.5)
        }
    }

    //更新完成
    private onUpdateFinish(key: string, needRestart: boolean) {
        Logger.log("onUpdateFinish=====main===", key, needRestart);
        if (key == VersionManager.Config_Key[0] && !needRestart) {
            this.setProgress(1)
            this.setProgressTip("更新完成...");
            this.startLoadingLocal();
        }
    }

    //加载本地文件到内存 
    private startLoadingLocal() {
        this.maxProgress = 0;
        let bundle: AssetManager.Bundle = ResourceManager.instance.bundleMap.get(this.bundleName);
        if (bundle) {
            this.startLoadNeed(bundle)
        } else {
            this.setProgress(this.maxProgress);
            this.setProgressTip("正在加载本地bundle:" + this.bundleName);
            ResourceManager.instance.loadBundle(this.bundleName, (loadedBundle: AssetManager.Bundle) => {
                this.maxProgress = 1
                this.setProgress(this.maxProgress);
                this.setProgressTip("正在加载本地bundle:" + this.bundleName);
                this.startLoadNeed(loadedBundle)
            })
        }
    }

    //开始加载需要文件 
    private startLoadNeed(bundle: AssetManager.Bundle) {
        this.maxProgress = 0;
        this.setProgressTip("正在认真加载本地资源,此过程不消化流量 " + (this.maxProgress * 100).toFixed(2) + "% ");
        Logger.log("startLoadNeed=", bundle, this.needLoadList)
        ResourceManager.instance.load(this.needLoadList, bundle, (completedCount: number, totalCount: number, item: any) => {
            let progress: number = completedCount / totalCount;
            if (progress > this.maxProgress) {
                this.maxProgress = progress;
            }
            this.setProgress(this.maxProgress);
            this.setProgressTip("正在认真加载本地资源,此过程不消化流量 " + (this.maxProgress * 100).toFixed(2) + "% ");
        }, (resource: any[]) => {
            this.setProgress(1);
            this.setProgressTip("加载本地资源完成");
            this.finishCallback && this.finishCallback(resource)
        })
    }

}

